<?php


header('Content-type:text');
define("TOKEN", "cfIlWNjt");


function getRealIp()
{
    $ip = '';
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
    else
        if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else
            if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
                $ip = getenv("REMOTE_ADDR");
            else
                if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
                    $ip = $_SERVER['REMOTE_ADDR'];
                else
                    $ip = "unknown";
    return ($ip);
}

function pre($data)
{
    echo '<pre>';
    var_dump($data);
}

include 'config.php';
include "./lib/WeChat.php";
include "./lib/mysql.class.php";

$wechatObj = new wechatCallbackapiTest($dbconfig);

if (!isset($_GET['echostr'])) {
    $wechatObj->responseMsg();
} else {
    $wechatObj->valid();
}


class wechatCallbackapiTest
{
    private $access_token = '';
    private $wxclass;
    private $db;

    public function __CONSTRUCT($dbconfig)
    {
        $this->wxclass = $wx = new Wechat(APPID, APPKEY);

        $this->access_token = $wx->getNormalAccessToken();
        $this->db = new MMysql($dbconfig);
    }

    private function curl_https($url, $data = array(), $header = array(), $timeout = 30)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
        if ($data) {
            ///	curl_setopt($ch, CURLOPT_POST, true);
            //	curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

        $response = curl_exec($ch);

        if ($error = curl_error($ch)) {
            die($error);
        }

        curl_close($ch);

        return $response;

    }

    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)) {
            $this->logger("R " . $postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);


            $this->addUserInfo($postObj);


            switch ($RX_TYPE) {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
            }
            $this->logger("T " . $result);
            echo $result;
        } else {
            echo "";
            exit;
        }
    }


    private function receiveEvent($object)
    {
        $openid = $object->FromUserName . '';
        $content = "";
        switch ($object->Event) {
            case "subscribe":


                $this->addUserInfo($object);

                $parent_id = (!empty($object->EventKey)) ? str_replace("qrscene_", "", $object->EventKey) : "0";

                if ($parent_id) {
                    $this->db->where("openId='" . $openid . "'")->update("users", array("parent_id" => $parent_id));
                    $this->db->doSql("update wx_users set `yue` = `yue`+0.03 where `id`=" . $parent_id);

                    $u = $this->db->where("openId='" . $openid . "'")->select("users");
                    $p = $this->db->where("id='" . $parent_id . "'")->select("users");

                    $data = array(
                        'first' => array('value' => urlencode("您好,您的红包已到账"), 'color' => "#000000"),
                        'keyword1' => array('value' => urlencode($u[0]['nickName']), 'color' => '#000000'),
                        'keyword2' => array('value' => urlencode("0.03元"), 'color' => '#000000'),
                        'keyword3' => array('value' => urlencode(date("Y-m-d H:i:s")), 'color' => '#000000'),
                        'remark' => array('value' => urlencode("您的好友绑定支付宝后，您可以获得0.5元现金红包"), 'color' => '#000000')
                    );
                    $this->doSend($p[0]['openId'], '9K8c81yx21dCgnvb8wVgcCi61D85MUmOe64OXpjXqvc', 'http://www.ls2346.com/b.php', $data, $topcolor = '#7B68EE');
                }


                $content = "欢迎您关注时尚便捷的快捷购物平台快闪手。
无限红包雨已经为你备妥，请赶紧领取。
友情提示：
回复“买xxx”，可快速寻找您需要购买的东西！例如您需要帽子，请回复“买帽子”。
本公众号每天12点、14点、16点、18点、20点、22点都有一次红包发放，请点击下方菜单“每日红包”领取
<a href='http://suo.im/481OSS'>双十一爆款清单</a>
<a href='http://suo.im/2GEBR5'>双十一预售清单</a>
<a href='http://suo.im/bBs5H'>双十一福利红包</a>
<a href='http://suo.im/4gbdlq'>双十一超级红包</a>
<a href='http://suo.im/1Qq9mT'>双十一各大会场入口</a>";

                break;
            case "unsubscribe":
                /*$isExt = $this -> db ->  where(" `openid`='$userId'") -> select("members");
				if($isExt[0]['parent_id']){
					$parent = $this -> db ->  where(" `uid`='{$isExt[0]['parent_id']}'") -> select("members");
					$this -> setJf($parent[0]['openid'],3,JIFEN,"您的好友【".$isExt[0]['nickname']."】逃跑了..");
				}*/
                break;
            case "SCAN":
                $this->addUserInfo($object);
                $content = "欢迎您关注时尚便捷的快捷购物平台快闪手，无限红包雨已经为你备妥，请赶紧领取。
友情提示：回复“买xxx”，可快速寻找您需要购买的东西！例如您需要帽子，请回复“买帽子”";
                break;
            case "CLICK":
                switch ($object->EventKey) {
                    case "每日红包":

                        $hbs = $this->db->where(time() . ">= `startTime` and " . time() . " <= `endTime` and `yilingquJine` <= `totalJinE`")->limit(1, 1)->order('`startTime` asc')->select('activity');//红包进行中

                        $str = $hbs[0]['kouling'] . "";
                        //$content = '000';
                        if ($str != "") {

                            //if(date("H",time()) == '12'){
                            //	$content = "恭喜您拿到今天的双十一福利红包淘口令，"."￥".$str."￥，". $hbs[0]['goodsdesc'];
                            //}else{
                            $content = str_replace("KOULING", $str, __KLDESC__) . $hbs[0]['goodsdesc'];
                            //}


                            //$cotnent .= $hbs[0]['goodsdesc'];
                            //$content = "44444";
                        } else {
                            $content = '红包还没开始哦';
                            $next = $this->db->where(time() . "<= `startTime`")->limit(1, 1)->order('`startTime` asc')->select('activity');//下一个红包
                            if ($next) {
                                $content = "距离红包活动开始还有 " . $this->ShengYu_Tian_Shi_Fen($next[0]['startTime'] . "，订上小闹钟，不要错过哦~");
                            }
                        }
                        $content .= '
--------------
本公众号每天12点、14点、16点、18点、20点、22点都有一次红包发放，请点击下方菜单“每日红包”领取';


                        break;
                    case "红包预报":
                        $content = array();
                        $content[] = array("Title" => "接下来有哪些红包呢？点击查看", "Description" => "不要错过任何一个红包！", "PicUrl" => "https://img.alicdn.com/imgextra/i2/98865373/TB2b2e9cT1z01JjSZFCXXXY.XXa_!!98865373.jpg", "Url" => "http://www.ls2346.com/wechat/hbyb.php");


                        $result = $this->transmitNews($object, $content);
                        break;
                    case "每日签到":

                        $isExt = $this->db->where("openId = '" . $object->FromUserName . "' and `qdtime` ='" . date('Y-m-d') . "'")->select("qiandao");

                        $content = array();
                        if (!$isExt) {


                            $code = str_replace(' ', '', md5(rand(11111111, 99999999) . rand(1111, 9999)));

                            $key = time();//函数在config.php

                            //$this -> db -> doSql("update wx_users set `yue` = `yue`+ 0.03 where `openId`='".$object->FromUserName."'");
                            $this->db->doSql("insert into wx_qiandao (`qdtime`,`openId`,`qdcode`,`isSucc`) values('" . date('Y-m-d') . "','" . $object->FromUserName . "','" . $code . "','0')");


                            $content[] = array("Title" => "恭喜您签到成功，获得0.06元红包，点击领取(此链接5分钟内有效)", "Description" => "点击领取", "PicUrl" => "https://img.alicdn.com/imgextra/i2/98865373/TB2b2e9cT1z01JjSZFCXXXY.XXa_!!98865373.jpg", "Url" => "http://www.ls2346.com/wechat/user_qiandao.php?key=" . $key . "&qdcode=" . $code);


                            //$content = "恭喜您今天签到成功，本次签到获得红包 0.03元";
                        } else {
                            $content[] = array("Title" => "已经签过到了哦，点击查看", "Description" => "点击领取", "PicUrl" => "https://img.alicdn.com/imgextra/i2/98865373/TB2b2e9cT1z01JjSZFCXXXY.XXa_!!98865373.jpg", "Url" => "http://www.ls2346.com/wechat/user.php");
                        }
                        //$content[] = array("Title"=>"双十一预售清单上线", "Description"=>"点击领取", "PicUrl"=>"https://img.alicdn.com/imgextra/i2/98865373/TB2b2e9cT1z01JjSZFCXXXY.XXa_!!98865373.jpg", "Url" =>"http://www.ls2346.com/wechat/tb/index2.php");

                        $content[] = array("Title" => "本公众号红包领取攻略", "Description" => "点击领取", "PicUrl" => "https://img.alicdn.com/imgextra/i2/98865373/TB2b2e9cT1z01JjSZFCXXXY.XXa_!!98865373.jpg", "Url" => "https://mp.weixin.qq.com/s?__biz=MzI5NTM0OTE4Mw==&mid=2247483666&idx=2&sn=d7bef5d442195096fdcf40ca84458a6b&chksm=ec55bfc2db2236d47e87c01d4110eb72600fbec24419d71b7294615c060eaabc7dea424b0ec5#rd");

                        $content[] = array("Title" => "2017双11红包攻略，双十一抢红包入口", "Description" => "点击领取", "PicUrl" => "https://img.alicdn.com/imgextra/i1/183575057/TB2kzwsj6uhSKJjSspaXXXFgFXa_!!183575057.png", "Url" => "http://www.ls2346.com/1111/index2.html");

                        $content[] = array("Title" => "2017双十一红包全攻略:玩转双11红包", "Description" => "点击领取", "PicUrl" => "https://img.alicdn.com/imgextra/i2/98865373/TB2b2e9cT1z01JjSZFCXXXY.XXa_!!98865373.jpg", "Url" => "http://www.ls2346.com/1111/index.html");

                        $result = $this->transmitNews($object, $content);

                        break;

                    case "个人海报":
                        $userId = $object->FromUserName;
                        $user = $this->db->where("openId='" . $userId . "'")->select("users");

                        $content[] = array("Title" => "怎样邀请好友", "Description" => "正确使用个人海报，可以领取更多红包哦~", "PicUrl" => "https://img.alicdn.com/imgextra/i2/98865373/TB2b2e9cT1z01JjSZFCXXXY.XXa_!!98865373.jpg", "Url" => "http://www.ls2346.com/wechat/user_yqhy.php");//TODO
                        $result = $this->transmitNews($object, $content);

                        if (is_file($user[0]['hb_path']) && (time() - $user[0]['hb_time'] < 3600 * 24 * 2)) {
                            $media_id = $user[0]['media_id'];
                        } else {


                            $this->_reply_customer($userId, '生成海报大约需要6秒钟，请等待。');

                            //=============
                            $imageInfo = $this->wxclass->getImg($user[0]['id'], 2);
                            $path = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . "pics" . DIRECTORY_SEPARATOR . date("Y/m/d") . DIRECTORY_SEPARATOR;
                            if (!is_dir($path)) {
                                @mkdir($path, 0777, 1);
                            }
                            $filename = $path . $userId . "_qr.jpg";

                            //写入数据库
                            //$this -> db -> where("openid = '$userId'") -> update("members",array('hb_time'=>time(),'hb_path'=>$filename));

                            //$this -> saveSess($userId,serialize($imageInfo));


                            $local_file = fopen($filename, 'w');

                            if (false !== $local_file) {
                                if (false !== fwrite($local_file, $imageInfo["body"])) {
                                    fclose($local_file);
                                }
                            }

                            $bg = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . "hb.jpg";
                            $target_file = $path . $userId . ".jpg";
                            //mergeImage("背景图片","二维码图片","生成后的路径","array(‘左边距’，‘上边距’,‘宽度’，‘高度’)");
                            //把二维码合成
                            $this->mergeImage($bg, $filename, $target_file, array('left' => 220, 'top' => 646, 'width' => 230, 'height' => 230));
                            //$this->mergeImage($bg,$filename, $target_file, array('left' => 156, 'top' => 340, 'width' => 307, 'height' => 307));
                            //合成昵称
                            //$this -> writeText($target_file, $target_file, "失效时间：".date("Y-m-d H:i:s",strtotime("+29 days")), array('size' => 18, 'left' => 145, 'top' => 1104));


                            //保存头像
                            /*			$avatarInfo = $this -> wxclass -> downloadImageFromWeiXin($user[0]['avatar']);
                                        $filename = $path.$userId."_avatar.jpg";
                                        $local_file = fopen($filename,'w');

                                        if(false !== $local_file){
                                            if(false !== fwrite($local_file,$avatarInfo["body"])){
                                                fclose($local_file);
                                            }
                                        }

                                        //合成头像
                                        $this->mergeImage($target_file,$filename, $target_file, array('left' => 40, 'top' => 767, 'width' => 88, 'height' => 88));
                            */
                            //上传海报到公众号，获取media_id
                            $media_id = $this->getMId($target_file);

                            //写入数据库
                            $this->db->where("openId = '$userId'")->update("users", array('hb_time' => time(), 'hb_path' => $target_file, 'media_id' => $media_id));

                        }
                        $this->_reply_customer($userId, $media_id, 'image');


                        break;


                    default:
                        $content = "功能开发中，敬请期待" . $object->EventKey;
                        break;
                }
                break;
            case "LOCATION":
                $content = "上传位置：纬度 " . $object->Latitude . ";经度 " . $object->Longitude;
                break;
            case "VIEW":
                $content = "跳转链接 " . $object->EventKey;
                break;
            case "MASSSENDJOBFINISH":
                $content = "消息ID：" . $object->MsgID . "，结果：" . $object->Status . "，粉丝数：" . $object->TotalCount . "，过滤：" . $object->FilterCount . "，发送成功：" . $object->SentCount . "，发送失败：" . $object->ErrorCount;
                break;
            default:
                $content = "receive a new event: " . $object->Event;
                break;
        }
        if (is_array($content)) {
            if (isset($content[0])) {
                $result = $this->transmitNews($object, $content);
            } else if (isset($content['MusicUrl'])) {
                $result = $this->transmitMusic($object, $content);
            }
        } else {
            $result = $this->transmitText($object, $content);
        }

        return $result;


        $content = "";
        switch ($object->Event) {
            case "subscribe":
                $content = "";
                break;
            case "unsubscribe":
                $content = "取消关注";
                break;
        }
        $result = $this->transmitText($object, $content);
        return $result;
    }


    public function _reply_customer($touser, $content, $type = 'text')
    {
        $ACC_TOKEN = $this->wxclass->getNormalAccessToken();
        $data = '';
        if ($type == 'text') {
            $data = '{
			"touser":"' . $touser . '",
			"msgtype":"' . $type . '",
			"text":
			{
				"content":"' . $content . '"
			}
		}';
        } elseif ($type == 'news') {
            $data = '{
    "touser":"' . $touser . '",
    "msgtype":"news",
    "news":{
        "articles": [
         {
             "title":"积分查询",
             "description":"积分查询",
             "url":"http://www.ls2346.com/web/index.php?uid=' . $content . '",
             "picurl":"http://d.hiphotos.baidu.com/zhidao/pic/item/7c1ed21b0ef41bd56e22cd6653da81cb39db3d2a.jpg"
         }
         ]
    }
}';
        } elseif ($type == 'image') {
            $data = array(
                "touser" => "$touser",
                "msgtype" => "$type",
                "image" => array("media_id" => $content));
            $data = json_encode($data);

        } else {
            $data = '{
			"touser":"' . $touser . '",
			"msgtype":"' . $type . '",
			"text":
			{
				"content":"测试"
			}
		}';
        }
//		$this -> saveSess($touser,$data);
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $ACC_TOKEN;

        $result = $this->_https_post($url, $data);
        $final = json_decode($result);
        return $final;
    }

    public function _https_post($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'Errno' . curl_error($curl);
        }
        curl_close($curl);
        return $result;
    }

    //接收文本消息
    private function receiveText($object)
    {
        $keyword = trim($object->Content);
        $content = "别急哦，红包正在路上....";
        $userId = $object->FromUserName . '';
        $result = "";

        if (is_array($content)) {
            if (isset($content[0]['PicUrl'])) {
                $result = $this->transmitNews($object, $content);
            } else if (isset($content['MusicUrl'])) {
                $result = $this->transmitMusic($object, $content);
            }
        } else {

            $result = $this->transmitMusic($object, 'HI');
        }

        return $result;
    }


    private function transmitText($object, $content)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

    private function transmitNews($object, $arr_item)
    {
        if (!is_array($arr_item))
            return;

        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($arr_item as $item)
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);

        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item));
        return $result;
    }

    private function transmitMusic($object, $musicArray)
    {
        $itemTpl = "<Music>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
    <MusicUrl><![CDATA[%s]]></MusicUrl>
    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";

        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    private function logger($log_content)
    {
        if (isset($_SERVER['HTTP_APPNAME'])) {   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        } else if ($_SERVER['REMOTE_ADDR'] != "127.0.0.1") { //LOCAL
            $max_size = 10000;
            $log_filename = "log.xml";
            //           if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            //           file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
        }
    }


    private function imagecreate($bg)
    {
        $bgImg = @imagecreatefromjpeg($bg);
        if (FALSE == $bgImg) {
            $bgImg = @imagecreatefrompng($bg);
        }
        if (FALSE == $bgImg) {
            $bgImg = @imagecreatefromgif($bg);
        }
        return $bgImg;
    }

    private function mergeImage($bg, $qr, $out, $param)
    {
        list($bgWidth, $bgHeight) = getimagesize($bg);
        list($qrWidth, $qrHeight) = getimagesize($qr);
        extract($param);
        $bgImg = $this->imagecreate($bg);
        $qrImg = $this->imagecreate($qr);
        imagecopyresized($bgImg, $qrImg, $left, $top, 0, 0, $width, $height, $qrWidth, $qrHeight);
        ob_start();
        // output jpeg (or any other chosen) format & quality
        imagejpeg($bgImg, NULL, 100);
        $contents = ob_get_contents();
        ob_end_clean();
        imagedestroy($bgImg);
        imagedestroy($qrImg);
        $fh = fopen($out, "w+");
        fwrite($fh, $contents);
        fclose($fh);
    }

    private function writeText($bg, $out, $text, $param = array())
    {
        list($bgWidth, $bgHeight) = getimagesize($bg);
        extract($param);
        $im = imagecreatefromjpeg($bg);
        $black = imagecolorallocate($im, 0, 0, 0);
        $font = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . "font" . DIRECTORY_SEPARATOR . 'msyhbd.ttf';
        //$text = 'hello';
        $white = imagecolorallocate($im, 128, 128, 128);
        imagettftext($im, $size, 0, $left, $top + $size / 2, $white, $font, $text);
        ob_start();
        // output jpeg (or any other chosen) format & quality
        imagejpeg($im, NULL, 100);
        $contents = ob_get_contents();
        ob_end_clean();
        imagedestroy($im);
        $fh = fopen($out, "w+");
        fwrite($fh, $contents);
        fclose($fh);
    }

    //发送模板消息
    public function doSend($touser, $template_id, $url, $data, $topcolor = '#7B68EE')
    {
        $ACC_TOKEN = $this->wxclass->getNormalAccessToken();
        /*
         * data=>array(
                'first'=>array('value'=>urlencode("您好,您已购买成功"),'color'=>"#743A3A"),
                'name'=>array('value'=>urlencode("商品信息:微时代电影票"),'color'=>'#EEEEEE'),
                'remark'=>array('value'=>urlencode('永久有效!密码为:1231313'),'color'=>'#FFFFFF'),
            )
         */
        $template = array(
            'touser' => $touser,
            'template_id' => $template_id,
            'url' => $url,
            'topcolor' => $topcolor,
            'data' => $data
        );
        $json_template = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $ACC_TOKEN;
        $dataRes = $this->_https_post($url, urldecode($json_template));
        if ($dataRes['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
    }

    //计算剩余时间
    public function ShengYu_Tian_Shi_Fen($unixEndTime = 0)
    {
        if ($unixEndTime <= time()) { // 如果过了活动终止日期
            return '已结束';
        }

        // 使用当前日期时间到活动截至日期时间的毫秒数来计算剩余天时分
        $time = $unixEndTime - time();

        $days = 0;
        if ($time >= 86400) { // 如果大于1天
            $days = (int)($time / 86400);
            $time = $time % 86400; // 计算天后剩余的毫秒数
        }

        $xiaoshi = 0;
        if ($time >= 3600) { // 如果大于1小时
            $xiaoshi = (int)($time / 3600);
            $time = $time % 3600; // 计算小时后剩余的毫秒数
        }


        $fen = (int)($time / 60); // 剩下的毫秒数都算作分

        $miao = $time - $fen * 60;


        return $days . '天' . $xiaoshi . '时' . $fen . '分' . $miao . '秒';
    }

    public function getMId($filename)
    {
        $ACC_TOKEN = $this->wxclass->getNormalAccessToken();
        $data = array(
            "media" => "@$filename"
        );
        $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=$ACC_TOKEN&type=image";

        $result = $this->_https_post($url, $data);
        $final = json_decode($result);
        return $final->media_id;
    }

}


?>